from exchange import Exchange
from time import time, sleep

def main():
    exchange = Exchange()
    login(exchange)
    loop(exchange)

##################################################
# Login

def login(exchange):
    username = raw_input("username: ")
    password = raw_input("password: ")
    exchange.login(username, password)

##################################################
# Loop

def loop(exchange):

    card = get_card(exchange)
    card_refreshed = time()
    card_index = 0
    
    last_status = "ACTIVE"
    last_delay = 0
    last_suspended = 0
    last_market = None
    
    while True:
    
        # Refresh the card once the specifed number of minutes since
        # the last refresh have elapsed. Find the index in the new card
        # of the market that is being priced.
        
        if card_refreshed < (time() - (30 * 60)):
            card_market = card[card_index]
            card = get_card(exchange)
            card_refreshed = time()
            card_index = get_card_index_of(card, cardMarket)
        
        market_summary = card[card_index]
        market_prices = None
        
        try:
            market_prices = exchange.get_market_prices(market_summary._exchangeId, market_summary._marketId)
            if market_prices._marketStatus == "ACTIVE":
                # If the market is ACTIVE, get the market itself in addition
                # to the prices - it's needed for the runner names.
                if last_market is None:
                    last_market = exchange.get_market(market_summary._exchangeId, market_summary._marketId)
            else:
                last_market = None
            print_market_info(market_summary, last_market, market_prices)

            prompt = True
            if market_prices._marketStatus == "SUSPENDED":
                # If the market is SUSPENDED and has been so for the
                # specified number of seconds, move to the next market
                # on the card - the market is probably SUSPENDED awaiting
                # settlement.
                if last_status != "SUSPENDED":
                    last_suspended = time()
                elif last_suspended < (time() - 15):
                    card_index = card_index + 1
            elif market_prices._marketStatus == "CLOSED":
                # If the market is CLOSED, move to the next market
                # on the card.
                card_index = card_index + 1
                prompt = False
            # else: Do nothing; keep pricing this market.

            last_status = market_prices._marketStatus
            last_delay = market_prices._delay

        except Exchange.ThrottleError:
            print "throttled"

        sleep(1)
        
        if prompt:
            answer = raw_input("press [enter] to continue; press [q] (then [enter]) to quit: ")
            if answer.strip() == "q":
                break

##################################################
# Market info method

def print_market_info(market_summary, market, market_prices):

    print "market id: exchange = %s; market = %s" % (market_summary._exchangeId, market_summary._marketId)
    print "market name: %s" % (market_summary._marketName)
    print "market status: %s" % (market_prices._marketStatus)
    if market_prices._marketStatus == "ACTIVE":
        if market_prices._delay > 0:
            print "in-play: yes; delay = %s" % (market_prices._delay)
        else:
            print "in-play: no"
    if not market is None:
        print "runners:"
        for runner in market._runners._Runner:
            runner_prices = Exchange.find_runner_prices(market_prices, runner._selectionId)
            back = "?"
            if len(runner_prices._bestPricesToBack._Price) > 0:
                back = runner_prices._bestPricesToBack._Price[0]._price
            lay = "?"
            if len(runner_prices._bestPricesToLay._Price) > 0:
                lay = runner_prices._bestPricesToLay._Price[0]._price
            print "  %s: back = %s; lay = %s" % (runner._name, back, lay)

##################################################
# Card methods

def get_card(exchange):

  # Ignore any markets with any of the following in the name.
  # The program prices only the who-will-win-this-race markets.

  ignores = ["(AvB)", "(Dist)", "(F/C)", "(Place)", "(RFC)", "(W/O)"]
  card = []
  
  events, market_summaries = exchange.get_events(13) # 13 = today's horse racing card
  for market_summary in market_summaries:
      ignored = False
      for ignore in ignores:
          if market_summary._marketName.find(ignore) != -1:
              ignored = True
              break
      if not ignored:
          card.append(market_summary)
  return card

def get_card_index_of(card, market_summary):
    index = 0
    for m in card:
        if (m._exchangeId == market_summary._exchangeId) and (m._marketId == market_summary._marketId):
            return index
        index = index + 1
    return index

if __name__ == "__main__":
    main()